//
//  KYTabBarButton.swift
//  NormalHE
//
//  Created by SHANGLU on 16/12/29.
//  Copyright © 2016年 heky. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
class KYTabBarButton: UIButton {

    dynamic var item:UITabBarItem!
    let TabBarButtonImageRadio:CGFloat = 0.7
    let disposeBag:DisposeBag = DisposeBag()
    private(set)var badgeButton:KYBadgeButton!
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //图片居中
        self.imageView?.contentMode = UIViewContentMode.Center
        //文字居中
        self.titleLabel?.textAlignment = .Center
        self.titleLabel?.font = UIFont.systemFontOfSize(13)
        self.setTitleColor(UIColor.blueColor(), forState: .Selected)
        self.setTitleColor(UIColor.blackColor(), forState: .Normal)
        let badgeButton = KYBadgeButton()
        self.addSubview(badgeButton)
        self.badgeButton = badgeButton
    
        self.rx_observe(UITabBarItem.self, "item").bindNext { [weak self](tabBarItem) in
            guard let tabBarItem = tabBarItem else{ return}
            self?.setTitle(tabBarItem.title, forState: .Normal)
            self?.setTitle(tabBarItem.title, forState: .Selected)
            self?.setImage(tabBarItem.image, forState: .Normal)
            self?.setImage(tabBarItem.selectedImage, forState: .Selected)
            self?.badgeButton.badgeValue = tabBarItem.badgeValue
            let badgeX = self!.frame.size.width - self!.badgeButton.frame.size.width - 20
            let badgeY:CGFloat = 0
            var badgeF = self!.badgeButton.frame
            badgeF.origin.x = badgeX
            badgeF.origin.y = badgeY
            self?.badgeButton.frame = badgeF
            
        }.addDisposableTo(disposeBag)
//        self.rx_observe(String.self, "item.badgeValue").bindNext { [weak self](value) in
//            self?.badgeButton.badgeValue = "10"
//            
//            }.addDisposableTo(disposeBag)

    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func imageRectForContentRect(contentRect: CGRect) -> CGRect {
        
        let imageW = contentRect.size.width
        let imageH = contentRect.size.height * TabBarButtonImageRadio
    
        return CGRect(x: 0, y: 0, width: imageW, height: imageH)
    }
    
    override func titleRectForContentRect(contentRect: CGRect) -> CGRect {
        
        let titleH = contentRect.size.height * (1 - TabBarButtonImageRadio)
        let titleY = contentRect.size.height * TabBarButtonImageRadio
        let titleW = contentRect.size.width
        return CGRect(x: 0, y: titleY , width: titleW, height: titleH)
    }

}
